import { defineConfig, loadEnv } from 'vite'
import { fileURLToPath, URL } from 'url'
//获取文件的路径
import path from 'path'
//import createVitePlugins from './vite/plugins'
import vue from '@vitejs/plugin-vue'
//导入SVG-icons
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
//导入mock
import { viteMockServe } from 'vite-plugin-mock'

import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Inspect from 'vite-plugin-inspect'

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  //获取各种环境下对应的变量
  //               环境文件  项目根目录
  // Load env file based on `mode` in the current working directory.
  // Set the third parameter to '' to load all env regardless of the `VITE_` prefix.
  // Default: 'development' for serve, 'production' for build
  const env = loadEnv(mode, process.cwd())
  const { VITE_APP_ENV } = env

  // console.log(import.meta.url)
  // console.log(import.meta)
  // console.log(fileURLToPath(new URL('./src', import.meta.url)))
  // console.log("dir: " + __dirname)
  // console.log(path.resolve(__dirname, './src'))

  return {
    // 部署生产环境和开发环境下的URL。
    // 默认情况下，vite 会假设你的应用是被部署在一个域名的根路径上
    // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上，你就需要用这个选项指定这个子路径。例如，如果你的应用被部署在 https://www.ruoyi.vip/admin/，则设置 baseUrl 为 /admin/。
    base: VITE_APP_ENV === 'production' ? '/' : '/',
    //plugins: createVitePlugins(env, command === 'build'),
    plugins: [
      vue(),
      AutoImport({
        // Auto import functions from Vue, e.g. ref, reactive, toRef...
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ['vue'],

        // Auto import functions from Element Plus, e.g. ElMessage, ElMessageBox... (with style)
        // 自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
        resolvers: [
          ElementPlusResolver(),

          // Auto import icon components
          // 自动导入图标组件
          IconsResolver({
            prefix: 'Icon',
          }),
        ],
        dts: path.resolve(path.resolve(__dirname, 'src'), 'auto-imports.d.ts'),
      }),
      //SVG-icons的配置
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: command === 'build',
      }),
      //mock的配置
      //https://blog.csdn.net/shanghai597/article/details/141604347
      viteMockServe({
        mockPath: 'mock', // mock文件夹路径
        enable: command === 'serve', // 只有开发环境才开启mock
        cors: true,
      }),
      Components({
        resolvers: [
          // Auto register icon components
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
          // Auto register Element Plus components
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
        ],

        dts: path.resolve(path.resolve(__dirname, 'src'), 'components.d.ts'),
      }),

      Icons({
        autoInstall: true,
      }),

      Inspect(),
    ],
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src'), //相对路径别名配置，@代表src
        // '@': fileURLToPath(new URL('./src', import.meta.url))
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.ts', '.js', 'tsx', '.jsx', '.json', '.vue'],
    },
    // vite 相关配置
    server: {
      port: 5173,
      // Default: '127.0.0.1'
      // Specify which IP addresses the server should listen on. Set this to 0.0.0.0 or true to listen on all addresses, including LAN and public addresses.
      host: true,
      // open: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_APP_BASE_URL, // 后端服务实际地址
          changeOrigin: true,
          // rewrite: (path) => path.replace(/^\/dev-api/, ""),
          // rewrite: (path) =>
          //   path.replace(new RegExp('^' + env.VITE_APP_BASE_API), ''),
        },
      },
    },

    //scss全局变量的配置
    css: {
      // preprocessorOptions: {
      //   scss: {
      //     javascriptEnabled: true,
      //     additionalData: '@import "./src/styles/variable.scss";',
      //   },
      // },
      //fix:error:stdin>:7356:1: warning: "@charset" must be the first rule in the file
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              },
            },
          },
        ],
      },
    },
  }
})
